import { Component, OnInit } from '@angular/core';
import {HttpClient,HttpErrorResponse} from "@angular/common/http";
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import { AuthTokenService } from '@services/auth-token.service';
import { EncryptService } from '@services/encrypt.service';
import { CommonResponse,CommonService,ToastColor,UpdateUserPasswordTypeEnum,VerificationType} from '@services/common-service.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { DefaultLanguageService } from '@services/default-language.service';
import {TranslateService} from '@ngx-translate/core';
@Component({
  selector: 'app-change-password',
  templateUrl: './change-password.page.html',
  styleUrls: ['./change-password.page.scss'],
})
export class ChangePasswordPage implements OnInit {

  constructor(private router:Router,
    private http:HttpClient,
    private authTokenService:AuthTokenService,
    private encryptService:EncryptService,
    private commonService:CommonService,
    private defaultLanguageService:DefaultLanguageService,
    private translate:TranslateService
  ) { }

  public loading:boolean = false;

  public i18n:any = {};

  public validateForm:FormGroup;  

  ngOnInit() {
    this.initLanguage();
    this.validateForm = new FormGroup({
      'oldPassword': new FormControl('', [
        Validators.required
      ]),
      'password':new FormControl('', [
        Validators.required,
        Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}')
      ]),
      'repeatPassword':new FormControl('', [
        Validators.required,
        Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}')
      ])
    },{
      updateOn:'blur',
      validators: this.passwordMatchValidator
    });
  }

  initLanguage(){
    this.i18n = this.commonService.initTranslate(['myAccount.setting.accountScurity.changePwdFunction']); 
  }

  passwordMatchValidator(formGroup:FormGroup) {
    let newPassword = formGroup.get('password').value;
    let repeatPassword = formGroup.get('repeatPassword').value;
    if(!newPassword || !repeatPassword || (newPassword == repeatPassword)){
      return {};
    }
    return {'notMatch':true};
  }

  get oldPassword(){return this.validateForm.get('oldPassword');}
  get password(){return this.validateForm.get('password');}
  get repeatPassword(){return this.validateForm.get('repeatPassword');}

  routeToResetPassword(){
    this.router.navigate(['/tabs/myAccount/setting/account-security/login-password/reset-password']);
  }

  updatePassword(){
    if(this.validateForm.invalid){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return false;
    }
    this.loading = true;
    let api = '/scm/app/updateUserPassword.do';
    let requestJson = {
      voUserApp:{
        appUserId:this.authTokenService.getAppUserId(),
        password:this.encryptService.md5Ecrypt(this.validateForm.value.password),
        oldPassword:this.encryptService.md5Ecrypt(this.validateForm.value.oldPassword),
      },
      updateUserPasswordType:UpdateUserPasswordTypeEnum.WITH_OLD_PASSWORD,
      verificationType:VerificationType.UPDATE_USER_PASSWORD_AFTER_LOGIN
    }
    this.http.post(api,requestJson).subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        this.commonService.commonToast(ToastColor.success,this.i18n.update_success);
        this.router.navigate(['/tabs/myAccount/setting/account-security']);
      }else{
        this.commonService.commonToast(ToastColor.warning,this.i18n.update_failed);
      }
      this.loading = false;
    },(errorResponse:HttpErrorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      this.loading = false;
    })
  }

}
